// pages/user/pages/bookInformation/bookInformation.js
var http = require('../../../../service/http.js');
var util = require('../../../../utils/util.js');
const app = getApp();
var todayStr = ''; //当前日期
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isshow: false, //是否展示蒙层
    showPage: false, //是否展示页面
    showDateBox: false, //显示日期选择框
    showCourseBox: false, //显示课程内容
    time: [
      ['00', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' 10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23'],
      ['00', '30']
    ], //预约时间
    //最终传递参数对象bookInfo
    chooseTime: '', //已选择时间
    field: [], //场次
    nofieldMsg: '', //场次日期提示
    chooseField: '', //已选场次名称
    chooseFieldId: '', // 已选场次id
    currentDate: '', //当前日期
    // chooseStartDate: '', //选择开始日期
    // chooseEndDate: '', //选择结束日期
    eccodenum: '', //验证码号
    personnel: '', //操作人

    //---------接收并展示的逻辑参数-------------
    bookInfo: '', //返回所有预约信息
    bookUser: '', //预约人
    bookPhone: '', //预约电话
    appointmentDateType: "", //0：日期范围:1：规定日期(根据这个判断是什么样的日期格式)
    appointmentDateRange: null, //appointmentDateType == 1 时预约日期范围[2018-10-10,2018-10-12]有固定日期的格式
    zjitemappointmentnums: '', //预约场次信息
    singleEccodeNum: '', //单码可预约次数 >1 显示验证码
    appointmentStartDate: '', //开始日期（号）appointmentStartDate
    appointmentEndDate: '', //结束日期appointmentEndDate
    appointmentDefaultNum: '', //购买数量以及做多可购买数量
    isAppointmentTime: '', //预约时间
    eccodenums: '', //验证码信息
    surplusNum: '', //剩余名额
    ecCodeArr: '', //验证码信息
    maxBookNum: '', //最大可预约次数/数量

    // －－－－－－日期选择器属性－－－－－－－－－－－－－－－－－－－－
    isShowAllDate: false, //是否展示全部日期
    scrollLeft: 0, //横向滚动条位置
    selectedDate: '', //选中的几月几号
    selectedWeek: '', //选中的星期几
    curYear: '', //当前年份
    curMonth: 0, //当前月份
    curHour: 0, //当前时间
    daysCountArr: [ // 保存各个月份的长度，平年
      31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    ],
    // weekArr: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    weekArr: ['一', '二', '三', '四', '五', '六', '日'],
    dateList: [],
    //时间区间形式
    // startDate: '2018-11-14', //开始日期（号）
    // endDate: '2019-12-20', //结束日期
    dateRange: [],

    selectDateStr: '', //已选日期
    monthList: [], //当月
    hasNextMonth: false, //是否显示下个月按钮
    hasPreMonth: false, //是否显示上个月按钮

    animation: '', //日期选择动画

    //－－－－－－－－表单验证－－－－－－－－－－－－－－－－－
    isValidateForm: false, //表单未完成验证，true--表单完成验证
    showBookSuccessPage: '', //显示预约成功页

    //请求参数

    itemid: '', //商品id
    skuid: '', //skuid
    orderId: '', //订单id

    curseInfos: [], //课程对象
    chooseCourse: '', //选中的预约课程
    selectCourseId: '', //已选课程id
    haveNoCourseDateMsg: '', //没有课程没有预约时间提示

    monthFirstDate: '', //日历第一天
    monthLastDate: '', //日历最后一天
    minAppointmentDate: '', //最小可预约日期（Date 截止日期）
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //接收itemid 用户名 电话
    console.log(options);
    let itemid = options.itemid; //商品id
    let skuid = options.skuid; //商品id
    let orderId = options.orderId; //orderId
    let bookUser = options.bookUser; //默认预约用户
    let bookPhone = options.bookPhone; //预约电话
    let eccode = options.eccode || ''; //默认卡号信息
    this.setData({
      bookUser: bookUser,
      personnel: bookUser, //操作人
      bookPhone: bookPhone,
      itemid: itemid, //商品id
      skuid: skuid, //skuid
      orderId: orderId, //订单id
      eccodenum: eccode, //默认开卡信息
    })

  },

  /**
   * 获取预约场次信息(计算剩余名额，建field场次信息)
   */
  getFieldInfo: function(zjitemappointmentnums) {
    if (!zjitemappointmentnums) { //根据日期查询场次
      let selectedDate = this.data.selectedDate;
      console.log("selectedDate.replace(/-/g, '')", selectedDate.replace(/-/g, ''));
      http.getReq('/weixin/appointment/getCanAppointmentNum', {
        itemId: this.data.itemid,
        appointmentDate: selectedDate.replace(/-/g, '')
      }, (res)=> {
        console.log('getFieldInfo', res);
        //获取剩余名额
        this.getSurplusNum(res.data);
        //默认场次和最大预约数量
        this.getDefaultField();
      });
    } else {
      this.getSurplusNum(zjitemappointmentnums); //获取剩余场次人数 
    }
  },

  /**
   * 获取剩余场次人数 
   */
  getSurplusNum: function(zjitemappointmentnums) {
    let field = [];
    let infoArray = [];
    for (let i = 0; i < zjitemappointmentnums.length; i++) {
      let infoObj = {};
      let surplusNum = '';
      if (zjitemappointmentnums[i].appointmentPlayMaxNum == null) {
        surplusNum = 'null'; //没有数量限制
        infoObj.surplusNum = surplusNum;
      } else {
        surplusNum = zjitemappointmentnums[i].appointmentPlayMaxNum - zjitemappointmentnums[i].appointmentPlayAlreadyNum
        infoObj.surplusNum = parseInt(surplusNum) < 0 ? 0 : parseInt(surplusNum);
      }

      infoObj.appointmentPlayName = zjitemappointmentnums[i].appointmentPlayName; //场次名称
      infoObj.id = zjitemappointmentnums[i].id;
      infoObj.itemId = zjitemappointmentnums[i].itemId;

      infoArray.push(infoObj);
      field.push(zjitemappointmentnums[i].appointmentPlayName);
    }
    this.setData({
      zjitemappointmentnums: infoArray, //场次及剩余名额信息
      field: field, //所有场次名称数组
    })
    //获取默认场次
  },
  /**
   * 选择场次和最大预约数量
   */
  getDefaultField: function() {
    let zjitemappointmentnums = this.data.zjitemappointmentnums; //预约场次信息
    let chooseFieldId = this.data.chooseFieldId; //预约场次id
    let [chooseField, surplusNum] = [this.data.chooseField, this.data.surplusNum]; //场次名称+ 剩余名额

    let hasSameFieldId = false; //选择的日期拥有同一场次信息
    if (chooseFieldId != '') { //在更换日期之前选择了场次
      for (let i = 0; i < zjitemappointmentnums.length; i++) {
        if (chooseFieldId = zjitemappointmentnums[i].id) {
          hasSameFieldId = true;
          break;
        }
      }
    }
    if (!hasSameFieldId) { //之前没有选择场次或没有找到相同场次
      this.setData({
        chooseField: zjitemappointmentnums[0].appointmentPlayName, //默认场次名称
        surplusNum: zjitemappointmentnums[0].surplusNum, //默认剩余名额
        chooseFieldId: zjitemappointmentnums[0].id, //默认预约场次id
      })
    }
    this.getMaxBookNum(); //获取最大可预约数量
  },
  /**
   * 获取最大可预约数量
   */
  getMaxBookNum: function() {
    let bookInfo = this.data.bookInfo;
    if (bookInfo.appointmentSetType == '1') { //课包类型产品，最大可预约数量为1;
      this.setData({
        maxBookNum: 1,
        bookNum: 1
      })
      return;
    }

    //根据 appointmentDefaultNum  和 surplusNum 可以得到最大预约数量
    let appointmentDefaultNum = this.data.appointmentDefaultNum; //购买数量
    let surplusNum = this.data.surplusNum; //剩余名额
    let maxBookNum = ''; //最大可购买数量
    if (surplusNum == 0) {
      maxBookNum = 0;
    } else if (surplusNum == 'null') {
      maxBookNum = appointmentDefaultNum;
    } else {
      maxBookNum = appointmentDefaultNum > surplusNum ? surplusNum : appointmentDefaultNum
    }

    console.log('maxBookNum', maxBookNum);
    this.setData({
      maxBookNum: maxBookNum,
      bookNum: 1
    })
  },

  /**
   * 增减预约数量
   */
  minsBookNum: function() {
    let bookNum = this.data.bookNum || this.data.maxBookNum;
    if (bookNum > 1) {
      bookNum--;
    } else {
      util.showToast('预约数量不能小于1', 1000, 'none', function() {});
      bookNum = 1;
    }
    this.setData({
      bookNum: bookNum
    })
  },
  addBookNum: function() {
    let bookNum = this.data.bookNum || this.data.maxBookNum;
    let maxBookNum = this.data.maxBookNum;
    let surplusNum = this.data.surplusNum; //剩余名额
    let appointmentDefaultNum = this.data.appointmentDefaultNum; //购买数量
    if (bookNum < maxBookNum) {
      bookNum++;
    } else {
      if (bookNum > appointmentDefaultNum) {
        util.showToast('预约数量不能大于购买数量', 1000, 'none', function() {});
      } else if (bookNum > surplusNum) {
        util.showToast('预约数量不能大于剩余名额', 1000, 'none', function() {});
      }
    }
    this.setData({
      bookNum: bookNum
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.data.shopInfoTimeOut === true) { //非分享且已经过期，清除店铺信息
      console.log('店铺信息已过期，重新加载 app.checkSession()');
      app.checkSession();
    }
    let [itemid, skuid, orderId] = [this.data.itemid, this.data.skuid, this.data.orderId];
    todayStr = util.currentDate(), //当前日期字符串2018-12-22
      this.getAppointmentInfo(itemid, skuid, orderId); //获取预约信息
  },
  /**
   * 预约场次变化
   */
  bindFieldPickerChange: function(e) {
    console.log('预约场次变化', e);
    let valueIndex = e.detail.value;
    let field = this.data.field; //场次信息
    let zjitemappointmentnums = this.data.zjitemappointmentnums; //预约信息
    let surplusNum = zjitemappointmentnums[valueIndex].surplusNum; //用于显示剩余名额

    let chooseFieldId = zjitemappointmentnums[valueIndex].id; //预约场次id
    let eccodenum = this.data.eccodenum || ''; //当前验证码

    this.setData({
      chooseField: field[valueIndex], //场次
      surplusNum: surplusNum < 0 ? 0 : surplusNum, //剩余名额
      chooseFieldId: chooseFieldId, //场次id
    })
    this.getMaxBookNum(); //获取最大可预约数量
  },

  /**
   * 预约时间发生变化
   */
  bindTimePickerChange: function(e) {
    console.log(e);
    let timeValue = e.detail.value; //时间数组[小时位置，分钟位置]
    let time = this.data.time; //所有时间
    let chooseTime = time[0][timeValue[0]] + ':' + time[1][timeValue[1]];
    console.log('chooseTime--' + chooseTime);
    this.setData({
      chooseTime: chooseTime
    })
  },

  /** 
   * 获取当前日期
   */
  getCurrentDate: function() {
    let dateRange = this.data.dateRange;
    let dateStr = dateRange.length > 0 ? dateRange[0].dateStr : '';

    let startDate = dateStr ? new Date(dateStr) : new Date(); //开始日期范围

    var y = startDate.getFullYear(); //年  
    var mon = startDate.getMonth() + 1; //月  
    var d = startDate.getDate(); //日  
    var i = startDate.getDay(); //星期  
    var h = startDate.getHours(); //小时

    this.setData({
      curYear: y,
      curMonth: mon,
      curHour: h,
      selectedDate: y + '-' + mon + '-' + d, //默认已选日期
      selectedWeek: this.data.weekArr[i]
    });

    this.getMonthList(); //获取scrollview 的时间列表
    this.getWeekList(y, mon - 1); //获取当月日历
    this.getTime();

  },


  //-------------------------------日期操作-------------------------------

  /**
   * 选择结束日期
   */
  bindEndDateChange: function() {
    console.log(e);
  },

  makeAnimation: function() {
    app.makeAnimation(); //弹出动画

    this.setData({
      animation: app.data.animationData,
    })

    setTimeout(()=> {
      this.setData({
        animation: app.data.animationData,
        isshow: app.data.isshow,
      })

    }, 50)
  },
  //关闭课程动画

  cancelAnimation: function() {
    app.cancelAnimation(); //弹出动画
    this.setData({
      animation: app.data.animationData,
    })

    setTimeout(()=> {
      this.setData({
        isshow: app.data.isshow,
        showDateBox: false,
      })
      console.log('animation', app.data.animationData)
    }, 200)

  },

  /**
   * 选择日期
   */
  selectDate: function(e) {
    console.log(e);
    let selectedDate = e.currentTarget.dataset.date.value;
    console.log('已选日期', selectedDate);
    this.setData({
      selectedDate: selectedDate,
      selectedWeek: this.data.weekArr[e.currentTarget.dataset.date.week]
    });

  },
  /**
   * 上一个月
   */
  preMonth: function() {

    var curYear = this.data.curYear;
    var curMonth = this.data.curMonth;
    curYear = curMonth - 1 ? curYear : curYear - 1;
    curMonth = curMonth - 1 ? curMonth - 1 : 12;
    this.setData({
      curYear: curYear,
      curMonth: curMonth
    });
    this.getWeekList(curYear, curMonth - 1);
  },
  /**
   * 下个月
   */
  nextMonth: function() {
    var curYear = this.data.curYear;
    var curMonth = this.data.curMonth;
    curYear = curMonth + 1 == 13 ? curYear + 1 : curYear;
    curMonth = curMonth + 1 == 13 ? 1 : curMonth + 1;
    this.setData({
      curYear: curYear,
      curMonth: curMonth
    });

    this.getWeekList(curYear, curMonth - 1);
  },


  /**
   * 获取日历Date
   */
  getWeekList: function(y, mon) {

    //如果是否闰年，则2月是29日
    var daysCountArr = this.data.daysCountArr;
    if (y % 4 == 0 && y % 100 != 0) {
      daysCountArr[1] = 29;
    }
    console.log('daysCountArr---', daysCountArr);
    //第几个月；下标从0开始实际月份还要再+1  
    var dateList = [];
    let monthList = [];
    dateList[0] = [];
    var weekIndex = 0; //第几个星期

    //日期范围
    let dateRange = this.data.dateRange;
    let selectDateStr = this.data.selectDateStr; //默认已选日期
    //如果开始时间小于今天的日期，那么开始时间改为今天
    console.log('daysCountArr[mon]', daysCountArr[mon]);
    for (var i = 0; i < daysCountArr[mon]; i++) {
      let day = i + 1;
      if (day < 10) {
        day = '0' + day
      }
      let currentDateStr = util.formateDateStr(y, (mon + 1), i + 1);
      let currentDate = new Date(currentDateStr);
      var week = new Date(y + '-' + (mon + 1) + '-' + day).getDay();

      let weekStr = '';
      let isvailable = -1;
      let appointmentNum = ''; //可预约数量
      switch (week) {
        case 0:
          weekStr = "周日";
          break;
        case 1:
          weekStr = "周一";
          break;
        case 2:
          weekStr = "周二";
          break;
        case 3:
          weekStr = "周三";
          break;
        case 4:
          weekStr = "周四";
          break;
        case 5:
          weekStr = "周五";
          break;
        case 6:
          weekStr = "周六";
          break;
      }
      for (let d = 0; d < dateRange.length; d++) {
        if (currentDateStr == dateRange[d].dateStr) { //日期包含在里面

          appointmentNum = dateRange[d].appointmentNum;
          //------------不可预约情况---------------------
          if (dateRange[d].isFull == 1) {
            isvailable = 0; //不可预约
            break;
          }
          let minAppointmentDate = this.data.minAppointmentDate;
          if (currentDate.getTime() < minAppointmentDate.getTime()) {
            isvailable = -2; //预约截止了
            break;
          }
          //------------可预约情况---------------------
          if (todayStr == currentDateStr) { //包含今日
            isvailable = 2;
            selectDateStr = selectDateStr ? selectDateStr : todayStr; //默认选择今天
          } else {
            isvailable = 1;
          }
          break;
        } else {
          continue;
        }
      }

      dateList[weekIndex].push({
        value: currentDateStr,
        date: i + 1,
        week: weekStr,
        isvailable: isvailable,
        appointmentNum: appointmentNum
      });

      if (week == 0 && i != (daysCountArr[mon] - 1)) {
        weekIndex++;
        dateList[weekIndex] = [];
      }
    }

    console.log('本月日期dateList', dateList);
    this.setData({
      showPage: true,
      dateList: dateList,
      selectDateStr: selectDateStr, //默认已选日期(如果可选日期包括当天，则默认选择日期为当天，没有则没有默认选择日期)
      daysCountArr: daysCountArr
    });
    //获取日期按钮显示
    this.getMonthBtn();
    //日期不为空,获取场次信息
    let bookInfo = this.data.bookInfo;
    if (selectDateStr != '' && bookInfo.appointmentSetType == '1') {
      util.throttle(this.getFieldInfoByCourseAndDate, 500)
    } else if (selectDateStr != '' && bookInfo.appointmentSetType != '1') { //根据默认选中日期查找场次
      this.getFieldInfo(); //查询场次信息
    }
  },
  //计算显示的预约时间（时间小于当前时间的不显示）
  getTime: function() {
    let curHour = this.data.curHour;
    console.log('getTime', curHour);
    let time = this.data.time;
    let timeHour = time[0]; //时间数组
    let newTimeHourArray = [];
    for (let i = 0; i < timeHour.length; i++) {
      if (parseInt(timeHour[i]) >= parseInt(curHour)) {
        newTimeHourArray.push(timeHour[i]);
      }
    }
    time[0] = newTimeHourArray;
    this.setData({
      time: time
    })

  },
  getMonthList: function() {
    let dateRange = this.data.dateRange;
    let dateStrLength = dateRange.length;
    let bookInfo = this.data.bookInfo;
    let minAppointmentDateStr = bookInfo.minAppointmentDate || '';
    let minAppointmentDate = new Date(minAppointmentDateStr);
    let weekStr = '';
    for (var i = 0; i < dateStrLength; i++) {
      let isvailable = 1;
      let dateStr = dateRange[i].dateStr;
      let date = new Date(dateStr);
      var week = date.getDay(); //获取星期

      switch (week) {
        case 0:
          weekStr = "周日";
          break;
        case 1:
          weekStr = "周一";
          break;
        case 2:
          weekStr = "周二";
          break;
        case 3:
          weekStr = "周三";
          break;
        case 4:
          weekStr = "周四";
          break;
        case 5:
          weekStr = "周五";
          break;
        case 6:
          weekStr = "周六";
          break;
      }
      dateRange[i].week = weekStr;
      dateRange[i].value = dateStr.substring(5, dateStr.length); //日期格式：11-01 

      if (minAppointmentDateStr != '' && (date.getTime() < minAppointmentDate.getTime())) { //小于预约截止天数，不可预约
        isvailable = -2;
      }
      dateRange[i].isvailable = isvailable;
    }
    console.log('dateRange', dateRange);
    this.setData({
      dateRange: dateRange,
      minAppointmentDate: minAppointmentDate, //最大可预约时间
    })
  },

  /**
   * 根据当前已选日期和   日历日期起始及结束日期判断是否加载（上个月或下个月）日历
   * 
   */
  compareDates: function() {
    this.getMonthDate(); //获取日历第一天与最后一天

    let selectDate = new Date(this.data.selectDateStr);

    //根据当前已选日期和   日历日期起始及结束日期判断是否加载（上个月或下个月）日历
    if (this.data.monthFirstDate.getTime() > selectDate.getTime()) {
      this.preMonth();
      // return 1;
    } else if (this.data.monthLastDate.getTime() < selectDate.getTime()) {
      this.nextMonth();
      // return 1
    }
  },
  //获取日历第一天与最后一天
  getMonthDate: function() {
    let monthList = []; //按月分组日期格式
    let dateList = this.data.dateList;
    for (let i = 0; i < dateList.length; i++) {
      monthList.push(...dateList[i]);
    }
    let monthFirstDate = new Date(monthList[0].value);
    let monthLastDate = new Date(monthList[monthList.length - 1].value);
    this.setData({
      monthFirstDate: monthFirstDate,
      monthLastDate: monthLastDate
    })
  },

  /**
   * 是否显示下一月按钮
   */
  getMonthBtn: function() {

    this.getMonthDate(); //获取日历的第一天与最后一天
    //显示的当月日期
    let dateList = this.data.dateList; //按星期分组日期格式

    //日期范围
    let dateRange = this.data.dateRange;
    let rangeFirstDate = new Date(dateRange[0].dateStr);
    let rangeLastDate = new Date(dateRange[dateRange.length - 1].dateStr);
    //对比日期
    let [hasNextMonth, hasPreMonth] = [false, false];

    if (this.data.monthFirstDate.getTime() > rangeFirstDate.getTime()) { //当月第一天 > 日期范围第一天
      hasPreMonth = true;
    }

    if (this.data.monthLastDate.getTime() < rangeLastDate.getTime()) { //当月最后一天 < 日期范围最后一天
      hasNextMonth = true;
    }

    this.setData({
      hasNextMonth: hasNextMonth,
      hasPreMonth: hasPreMonth,
    })
  },
  /**
   * 选择（scrollView中的）日期 查找场次信息
   */
  handlerSelectDate: function(e) {
    console.log('选择日期：handlerSelectDate', e);

    let bookInfo = this.data.bookInfo;
    let appointmentSetType = bookInfo.appointmentSetType;
    if (e) {
      let dateRange = this.data.dateRange;
      let dateIndex = e.currentTarget.dataset.dateindex; //选择日期下标
      this.setData({
        selectDateStr: dateRange[dateIndex].dateStr
      })

    }

    if (appointmentSetType == '1') { //根据课程查场次
      util.throttle(this.getFieldInfoByCourseAndDate, 500)
    } else {
      this.getFieldInfo(); //查询场次信息
    }

    this.compareDates(); //根据已选日期获取当月日历
  },
  /**
   *根据课程和日期查场次
   */
  getFieldInfoByCourseAndDate: function() {
    http.getReq('/weixin/appointment/getCurseCanAppointmentNum', {
      curseInfoId: this.data.selectCourseId || '', //课程id
      zjItemAppointmentId: this.data.bookInfo.id, //预约要素id
      appointmentDate: this.data.selectDateStr, //预约日期
    }, (res)=> {
      console.log('根据课程查场次', res);
      if (res.ret) { //获取场次信息
        this.getFieldInfo(res.data);
        this.setData({
          chooseField: '', //场地信息
          nofieldMsg: '', //场次日期提示
          chooseFieldId: '', //场地信息id
        })
      } else { //根据该日期查不到场次信息

        let nofieldMsg = '根据该日期查不到场次信息,请更换其他日期'; //场次日期提示
        this.setData({
          nofieldMsg: nofieldMsg,
          zjitemappointmentnums: [], //场次及剩余名额信息
          field: [], //所有场次名称数组
          chooseField: '', //已选场次信息
          chooseFieldId: '', //场地信息id
        })
      }
    })
  },

  /**
   * 展示所有日期
   */
  showAllDate: function() {
    this.setData({
      isshow: true,
      isShowAllDate: true
    })
  },
  /**
   * 选择展开的日期   
   */
  handlerSelectDay: function(e) {
    console.log('handlerSelectDay', e);
    let weekindex = e.currentTarget.dataset.weekindex;
    let dayIndex = e.currentTarget.dataset.dayindex;
    let dateRange = this.data.dateRange;
    let selectDateStr = this.data.dateList[weekindex][dayIndex].value;
    console.log('selectDateStr', selectDateStr);
    this.setData({
      selectDateStr: selectDateStr
    })
    this.closeDateModel();
    for (let i = 0; i < dateRange.length; i++) {
      if (selectDateStr == dateRange[i].dateStr) {
        this.countWidth(i);
      }
    }

    let bookInfo = this.data.bookInfo;
    let appointmentSetType = bookInfo.appointmentSetType;
    if (appointmentSetType == '1') { //根据课程查场次
      util.throttle(this.getFieldInfoByCourseAndDate, 500)
    } else {
      this.getFieldInfo(); //查询场次信息
    }

  },
  //关闭全部日期块
  closeDateModel: function() {
    this.setData({
      isshow: false, //是否展示蒙层
      isShowAllDate: false, //是否展示全部日期
    })
  },

  /**
   * 模态框
   */
  closeModel: function() {
    this.setData({
      isshow: false, //是否展示蒙层
      isShowAllDate: false, //是否展示全部日期
    })
  },

  /**
   * 计算scroll-view显示日期块的宽度（用于定点跳转）
   */
  countWidth: function(dayIndex) {
    wx.createSelectorQuery().select('.dayBlock').boundingClientRect((rect) =>{
      this.setData({
        scrollLeft: rect.width * (dayIndex - 2)
      })
      console.log(rect)
    }).exec()
  },

  //------保存预约信息----------------------------------------------
  saveBookInfo: function(e) {
    console.log("saveBookInfo", e)
    
    this.validateInfo(e);
    let isValidateForm = this.data.isValidateForm;
    let [itemId, skuId, orderId, personnel] = [this.data.itemid, this.data.skuid || '', this.data.orderId, this.data.personnel];
    if (isValidateForm) { //提交表单
      http.getReq('/weixin/appointment/save', {
        itemId: itemId,
        skuId: skuId,
        orderId: orderId,
        createUser: personnel || '',
        appointmentDate: e.detail.value.selectDateStr ? e.detail.value.selectDateStr.replace(/-/g, '') : '', //预约日期
        appointmentTime: e.detail.value.chooseTime || '', //预约时间
        appointmentPeople: e.detail.value.bookUser || '', //预约人 
        appointmentPhone: e.detail.value.bookPhone || '', //预约电话
        appointmentQuantity: e.detail.value.bookNum || '', //预约数量
        appointmentPlayName: e.detail.value.chooseField || '', //预约场次名称
        zjitemappointmentnumId: this.data.chooseFieldId || '', //预约场次id
        eccode: e.detail.value.eccodenum || '', //已选择验证码
        curseInfoId: this.data.selectCourseId, //已选课程id
        zjcurseappointmentnumId: this.data.chooseFieldId, //课程场次id
        appointmentSetType: this.data.bookInfo.appointmentSetType, //是否有课包
      }, (res)=> {
        console.log('提交预约', res);
        if (res.ret) {

        } else {
          util.showToast(res.msg, 1500, 'none', function() {});
        }
        this.setData({
          showBookSuccessPage: res.ret
        })

      });

    }
  },
  //验证消息
  validateInfo: function(e) {

    let bookInfo = this.data.bookInfo; //预约信息
    let selectDateStr = e.detail.value.selectDateStr; //预约开始日期
    let chooseTime = e.detail.value.chooseTime; //预约时间
    let chooseField = e.detail.value.chooseField; //预约场次
    let surplusNum = e.detail.value.surplusNum; //场次剩余数量
    let bookNum = e.detail.value.bookNum;
    let bookUser = e.detail.value.bookUser;
    let bookPhone = e.detail.value.bookPhone;
    let appointmentDateType = this.data.appointmentDateType;
    let msg = ''; //提示信息
    let isValidateForm = false;

    //验证手机号码：
    this.testPhone(e);
    if (selectDateStr === '') {
      msg = "请选择预约日期"
    } else if (chooseTime === '' && bookInfo.isAppointmentTime == '1') {
      msg = "请选择预约时间"
    } else if (chooseField === '') {
      msg = "请选择预约场次"
    } else if (bookNum === '') {
      msg = "请填写预约数量"
    } else if (bookUser === '') {
      msg = "请选填写预约人"
    } else if (bookPhone === '') {
      msg = "请填写预约联系电话"
    }

    if (msg === '') {
      isValidateForm = true;
      let isPhone = this.testPhone(bookPhone);
      if (!isPhone) {
        util.showToast('手机号有误', 1500, 'none', function() {});
        isValidateForm = false;
      }
      if (surplusNum == 0) {
        util.showToast('剩余数量为0，请更换其他场次', 1500, 'none', function() {});
        isValidateForm = false;
      }
      if (parseInt(bookNum) == 0) {
        util.showToast('可预约数量不能为0', 1500, 'none', function() {});
        isValidateForm = false;
      }
      if (parseInt(bookNum) > parseInt(surplusNum)) {
        util.showToast('可预约数量不超过' + surplusNum, 1500, 'none', function() {});
        isValidateForm = false;
      }

    } else {
      util.showToast(msg, 1000, 'none', function() {});
      isValidateForm = false;
    }
    this.setData({
      isValidateForm: isValidateForm
    })

  },
  testPhone: function(phoneNum) {
    let isPhone = '';
    if (phoneNum.length >= 11) {
      if (!(/^1[23456789]\d{9}$/.test(phoneNum))) {
        isPhone = false;

      } else {
        isPhone = true;
      }
    } else {
      isPhone = false;
    }
    return isPhone;
  },
  // 选择验证码号
  bindCodeChange: function(e) {
    console.log(e);
    let valueIndex = e.detail.value;
    let ecCodeArr = this.data.ecCodeArr; //验证码信息：验证码+ 可预约次数
    let eccodenums = this.data.eccodenums; //所有验证码
    let appointmentDefaultNum = ecCodeArr[valueIndex].appointmentDefaultNum; //可预约次数

    this.setData({
      eccodenum: eccodenums[valueIndex], //已选择验证码
      appointmentDefaultNum: appointmentDefaultNum
    });
    this.getMaxBookNum();
  },
  /**
   * 查询预约商品详细信息
   */
  getAppointmentInfo: function(itemid, skuid, orderId) {
    console.log('getAppointmentInfo');
    http.getReq('/weixin/appointment/getSettingsNewCalendar', {
      itemid: itemid,
      skuid: skuid,
      orderId: orderId
    }, (res)=> {
      console.log('getAppointmentInfo', res);
      if (res.ret) {
        let bookInfo = res.data; //返回预约信息

        let zjitemappointmentnums = res.data.zjitemappointmentnums;
        let appointmentDateType = res.data.appointmentDateType; //验码类型
        let appointmentDateRange = res.data.appointmentDateRange; //固定日期--array
        let singleEccodeNum = res.data.singleEccodeNum; //单码可验证次数
        let appointmentDefaultNum = res.data.appointmentDefaultNum || ''; //
        this.getFieldInfo(zjitemappointmentnums); //获取剩余数量


        this.setData({
          appointmentDateType: appointmentDateType,
          appointmentDateRange: appointmentDateRange,
          singleEccodeNum: res.data.singleEccodeNum, //可验码次数
          dateRange: res.data.dateRange || [], //可预约日期范围

          bookInfo: bookInfo,
          appointmentDefaultNum: appointmentDefaultNum, //购买数量
          curseInfos: res.data.curseInfos || [], //课程信息
        })

        //单码多验证(优惠次卡)
        if (singleEccodeNum > 1) {
          this.getEcCodeArr(bookInfo); //获取预约信息
        }
        if (bookInfo.appointmentSetType != "1") { //没有课包，显示日期
          //设置日期列表
          this.getCurrentDate();
        } else { //有课包，设置课包选项
          this.setCourObj();
        }


      }
    });
  },
  /**
   * 获取默认预信息
   */
  getEcCodeArr: function(bookInfo) {
    console.log('bookInfo.ecCodeAr', bookInfo.ecCodeArr)
    let eccodenums = []; //保存所有验证码
    let ecCodeArr = []; //验证码所有信息arr
    let appointmentDefaultNum = ''; //购买数量/单码可预约次数 
    let eccodenum = this.data.eccodenum; //默认开卡信息
    console.log('eccodenum', eccodenum);

    if (bookInfo.singleEccodeNum == 1) {
      appointmentDefaultNum = bookInfo.appointmentDefaultNum;
    } else if (bookInfo.singleEccodeNum > 1) {
      ecCodeArr = bookInfo.ecCodeArr;
      for (let i = 0; i < ecCodeArr.length; i++) { //eccodenums 用于ecCodePicker数组 用于显示
        if (eccodenum == ecCodeArr[i].EcCode) { //默认最大可用次数
          appointmentDefaultNum = ecCodeArr[i].appointmentDefaultNum;
        }
        eccodenums.push(ecCodeArr[i].EcCode);
      }
    }

    this.setData({
      ecCodeArr: ecCodeArr, //验证码信息
      eccodenums: eccodenums, //验证码数组
      eccodenum: eccodenum,
      appointmentDefaultNum: appointmentDefaultNum
      // eccodenum: ecCodeArr[0].EcCode, //默认显示验证码
      // bookNum: ecCodeArr[0].appointmentDefaultNum, //可预约数量
    })

  },
  /**
   * 预约成功查看订单
   */
  backToOrder: function() {
    wx.navigateBack({
      delta: 1,
    })
  },
  /**
   * 校验预约数量
   */
  handleBookNum: function(e) {
    console.log('校验预约数量', e);
    let bookNum = e.detail.value;
    let maxBookNum = this.data.maxBookNum;
    let surplusNum = this.data.surplusNum; //剩余名额
    let appointmentDefaultNum = this.data.appointmentDefaultNum; //购买数量
    if (bookNum > maxBookNum) {
      if (bookNum > appointmentDefaultNum) {
        util.showToast('预约数量不能大于购买数量', 1000, 'none', function() {});
      } else if (bookNum > surplusNum) {
        util.showToast('预约数量不能大于剩余名额', 1000, 'none', function() {});
      }
      bookNum = maxBookNum;
    } else if (bookNum < 1) {
      bookNum = 1;
      util.showToast('预约数量不能小于1', 1000, 'none', function() {});
    }
    this.setData({
      bookNum: bookNum
    })
  },
  /**
   * 最大可预约数量/次数提示
   */
  handleTip: function() {
    // let sing
    let bookNum = this.data.bookNum;
    let maxBookNum = this.data.maxBookNum;
    let singleEccodeNum = this.data.singleEccodeNum;
    //查验是否为课包类型商品
    let msg = '';
    let bookInfo = this.data.bookInfo;
    if (bookInfo.appointmentSetType == '1') {
      msg = '课包类商品最大可预约数量为1';
    }
    if (singleEccodeNum > 1) {
      util.showToast(msg || '最大可预约次数为' + maxBookNum, 1000, 'none', function() {});
    } else {
      util.showToast('最大可预约数量为' + maxBookNum, 1000, 'none', function() {});
    }
  },
  /**
   * 选择预约课程
   */
  chooseCourse: function(e) {
    console.log('选择预约课程', e);

    this.makeAnimation();
    this.setData({
      showCourseBox: true
    })
  },
  /**
   * 选择课程
   */
  selectCourse: function(e) {
    console.log(' 选择课程', e);

    let index = e.currentTarget.dataset.index;
    let curseInfos = this.data.curseInfos;
    // let chooseCourse = this.data.chooseCourse;//已选课程
    // if (chooseCourse != '' && chooseCourse == curseInfos[index].curseName){
    //   return;
    // }

    for (let i = 0; i < curseInfos.length; i++) { //改变其他选项状态
      if (index == i) {
        curseInfos[i].checked = true;
      } else {
        curseInfos[i].checked = false;
      }
    }

    this.setData({
      // chooseCourse: curseInfos[index].curseName,
      // selectCourseId: curseInfos[index].curseInfoId,
      curseInfos: curseInfos
    })
  },
  /**
   * 合成课程对象
   */
  setCourObj: function() {

    let newCurseInfos = [];
    let curseInfos = this.data.curseInfos; //课程对象数组
    for (let i = 0; i < curseInfos.length; i++) {
      let courObj = {};
      courObj.checked = false;
      courObj.curseInfoId = curseInfos[i].curseInfoId;
      courObj.curseName = curseInfos[i].curseName;
      newCurseInfos.push(courObj);
    }
    this.setData({
      curseInfos: newCurseInfos, //课包信息
      showPage: true, //加载完课包展示页面
    })
  },
  /**
   * 确定预约课程
   */
  confirmCourse: function() {
    let chooseCourse = this.data.chooseCourse;
    let curseInfos = this.data.curseInfos;

    let selectCourseName = '';
    let selectCourseId = '';
    curseInfos.forEach((item, index) => {
      console.log('item', item);
      if (item.checked) {
        selectCourseName = item.curseName;
        selectCourseId = item.curseInfoId;
      }
    })
    if (selectCourseName == '') {
      util.showToast('请选择预约课程', 1000, 'none', function() {});
      return
    } else if (selectCourseName == chooseCourse) { //如果两次选择课程相等 不更改数据
      this.cancelAnimation(); //关闭选择框
      return
    }
    this.setData({
      chooseCourse: selectCourseName, //已选课程
      selectCourseId: selectCourseId, //课程id
    })

    this.cancelAnimation();
    //根据选择课程查询日期
    this.queryDateRangeByCourse();
  },
  /**
   * 根据选择课程查找日期内容
   */
  queryDateRangeByCourse: function() {
    http.getReq('/weixin/appointment/getCurseDateRang', {
      zjItemAppointmentId: this.data.bookInfo.id,
      curseInfoId: this.data.selectCourseId
    }, (res)=> {
      console.log('queryDateRangeByCourse', res);
      if (res.ret) {
        this.setData({
          dateRange: res.data || '',
          haveNoCourseDateMsg: ''
        })
        console.log('dateRange', this.data.dateRange);
        this.getCurrentDate(); //获取当前日期以及可预约日期和时间

      } else { //该课程没有可预约的日期
        this.setData({
          haveNoCourseDateMsg: '没有可预约日期请更换其他课程',
          selectDateStr: '', //已选日期时间
          dateRange: [],
          chooseField: '',

        })
      }
    })
  },
  // 超出可预约范围提示
  outOfDateTip: function() {
    util.showToast('超出可预约时间范围', 800, 'none');
  },
  /**
   * 场次停止预约提示
   */
  overDateTip: function() {
    util.showToast('该场次已停止预约，请选择其他日期。', 800, 'none');
  }
})